package com.fan.shop.businesslogic;

import java.util.List;

import org.apache.log4j.Logger;

import com.fan.shop.domain.StockReq;
import com.fan.shop.global.ShopGlobalVariables;
import com.fan.shop.model.userclass.StockReqLineUserClass;
import com.fan.shop.process.ProcExec;
import com.fan.shop.services.StockReqLineService;
import com.fan.shop.services.StockReqService;

public class StockReqCancelProcess extends ProcExec<Integer> {

	private static Logger logger = Logger
			.getLogger(StockReqCancelProcess.class);
	private String requisitionNo;

	private StockReqService stockReqService;
	private StockReqLineService stockReqLineService;

	private List<StockReqLineUserClass> attachedLines;

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		StockReqCancelProcess.logger = logger;
	}

	public String getRequisitionNo() {
		return requisitionNo;
	}

	public void setRequisitionNo(String requisitionNo) {
		this.requisitionNo = requisitionNo;
	}

	public StockReqService getStockReqService() {
		return stockReqService;
	}

	public void setStockReqService(StockReqService stockReqService) {
		this.stockReqService = stockReqService;
	}

	public StockReqLineService getStockReqLineService() {
		return stockReqLineService;
	}

	public void setStockReqLineService(StockReqLineService stockReqLineService) {
		this.stockReqLineService = stockReqLineService;
	}

	public List<StockReqLineUserClass> getAttachedLines() {
		return attachedLines;
	}

	public void setAttachedLines(List<StockReqLineUserClass> attachedLines) {
		this.attachedLines = attachedLines;
	}

	@Override
	public Integer processImpl() {
		
		if(!stockReqService.hasStockReq(requisitionNo))
		{
			setErrorMessage("Stock Req: " + requisitionNo + " doesn't exist!");
			return ShopGlobalVariables.FAILED;
		}
		
		StockReq stockReq = stockReqService.getStockReq(requisitionNo);
		stockReq.setStatus(ShopGlobalVariables.CANCELLED);
		for(StockReqLineUserClass lineUserClass : attachedLines)
		{
			StockReqLineCancelProcess stockReqLineCancelProcess = new StockReqLineCancelProcess();
			stockReqLineCancelProcess.setRequisitionNo(requisitionNo);
			stockReqLineCancelProcess.setItemCode(lineUserClass.getItemCode());
			
			stockReqLineCancelProcess.setStockReqLineService(stockReqLineService);
			int result = stockReqLineCancelProcess.process();
			if(result == ShopGlobalVariables.FAILED)
			{
				setErrorMessage(stockReqLineCancelProcess.getErrorMessage());
				return ShopGlobalVariables.FAILED;
			}
		}
		stockReqService.updateStockReq(stockReq);
		return ShopGlobalVariables.SUCCESS;
	}

}
